import { Form, Input, Select } from "antd"
import { FC, useEffect } from "react"
import { useComponentsStore } from "../../editor/stores/components"
import {
  ComponentConfig,
  ComponentSetter,
  useComponentConfigStore,
} from "../../editor/stores/component-config"

interface ComponentAttrProps {}

const ComponentAttr: FC<ComponentAttrProps> = () => {
  const [form] = Form.useForm()

  const { curComponent, curComponentId, updateComponentProps } =
    useComponentsStore()
  const { componentConfig } = useComponentConfigStore()

  useEffect(() => {
    const data = form.getFieldsValue()
    form.setFieldsValue({ ...data, ...curComponent?.props })
  }, [curComponent])

  if (!curComponentId || !curComponent) return null

  const renderFormElement = (setting: ComponentSetter) => {
    const { type, options } = setting

    if (type === "select") {
      return <Select options={options} />
    } else if (type === "input") {
      return <Input />
    }
  }

  const valueChange = (changeValues: ComponentConfig) => {
    if (curComponentId) {
      updateComponentProps(curComponentId, changeValues)
    }
  }

  return (
    <Form
      form={form}
      onValuesChange={valueChange}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 14 }}
    >
      <Form.Item label="组件id">
        <Input value={curComponentId} disabled />
      </Form.Item>
      <Form.Item label="组件名称">
        <Input value={curComponent.name} disabled />
      </Form.Item>
      <Form.Item label="组件描述">
        <Input value={curComponent.desc} disabled />
      </Form.Item>
      {componentConfig[curComponent.name]?.setter?.map((setting) => (
        <Form.Item label={setting.label} key={setting.label}>
          {renderFormElement(setting)}
        </Form.Item>
      ))}
    </Form>
  )
}

export default ComponentAttr
